<?php defined('SYSPATH') or die('No direct access allowed.');

class Auth_Redis extends Auth
{

	// Redis
	private $r;
	private $_user;

	/**
	 * Constructor loads the user list into the class.
	 */
	public function __construct($config = array())
	{
		parent::__construct($config);

		// Load user list
		$this->r = RedisDB::instance();
	}

	/**
	 * Logs a user in.
	 *
	 * @param   string   username
	 * @param   string   password
	 * @param   boolean  enable autologin (not supported)
	 * @return  boolean
	 */
	protected function _login($username, $password, $remember)
	{
		if (is_string($password))
		{
			// Create a hashed password
			$password = $this->hash($password);
			//echo $password;
			//$user_id = $this->r->hGet('users:lookup:username',$username);
			//$this->_user = json_decode($this->r->get('users:'.$user_id));
			//exit($this->complete_login($username));
		}
        if ($user_id = $this->r->hGet('users:lookup:username',strtolower($username)))
        {        	$this->_user = json_decode($this->r->get('users:'.$user_id));
        	if ($this->_user->password === $password)
        	{        		return $this->complete_login($username);        	}
        }
		// Login failed
		return FALSE;
	}

	/**
	 * Forces a user to be logged in, without specifying a password.
	 *
	 * @param   mixed    username
	 * @return  boolean
	 */
	public function force_login($username)
	{
		// Complete the login
		return $this->complete_login($username);
	}

	/**
	 * Get the stored password for a username.
	 *
	 * @param   mixed   username
	 * @return  string
	 */
	public function password($username)
	{
        if ($user_id = $this->r->hGet('users:lookup:username',strtolower($username)))
        {
        	$user = json_decode($this->r->get('users:'.$user_id));
        	return $user->password;
        }
        return FALSE;
	}

	/**
	 * Compare password with original (plain text). Works for current (logged in) user
	 *
	 * @param   string  $password
	 * @return  boolean
	 */
	public function check_password($password)
	{
		$username = parent::get_user($default);

		if ($username === FALSE)
		{
			return FALSE;
		}

		return ($password === $this->password($username));
	}

/*
    public function logged_in($role = NULL)
    {
        // Check to see if the user is logged in, and if $role is set, has all roles
    }
*/
    public function get_user($default = NULL)
    {
		$username = parent::get_user($default);

        if ($user_id = $this->r->hGet('users:lookup:username',strtolower($username)))
        {
        	return json_decode($this->r->get('users:'.$user_id));
        }

		//return $user;
		return FALSE;
    }
}